#!/usr/bin/python

# Copyright 2009 Nathan Michaels
#
# This file is part of jen-breakout.
#
# jen-breakout is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# jen-breakout is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with jen-breakout.  If not, see <http://www.gnu.org/licenses/>.

import sys
import os
import dircache

COLUMNS = 32

RED    = 1
ORANGE = 2
YELLOW = 3
GREEN  = 4
BLUE   = 5
PURPLE = 6
NONE   = 0

colors = {
    'R':RED,
    'r':RED,
    'o':ORANGE,
    'y':YELLOW,
    'g':GREEN,
    'b':BLUE,
    'p':PURPLE,
    '0':NONE,
    '_':NONE,
    '-':NONE,
    ' ':NONE
}

class Level (object):
    def __init__ (self):
        self.firstRow = 100
        self.lastRow = 0
        self.name = "Unnamed"
        self.rows = []

    def __str__ (self):
        # First, the header
        s = '''
static level_t %s =
{
    .firstRow = %d,
    .lastRow  = %d,
    .level    =
    {
''' % (self.name, self.firstRow, self.lastRow)

        # First rows
        if self.firstRow > 0:
            s += '        [0 ... %d] = ' % (self.firstRow - 1,)
            s += '{%s},' % (','.join (['0' for col in range (COLUMNS)]),)

        # Interesting rows
        for row in self.rows[self.firstRow:self.lastRow+1]:
            s += '        {'
            s += ','.join ([str(color) for color in row])
            s += '},\n'

        # Last rows
        s += '        [%d ... BRICK_ROWS - 1] = ' % (self.lastRow + 1)
        s += '{%s}' % (','.join (['0' for col in range (COLUMNS)]),)
        s += '    }\n};'

        return s
    

def Levelify (fileName):
    level = Level ()
    level.name = fileName[:fileName.index ('.')]
    level.rows = []
    text = open (fileName).read ()
    text = text.strip ()
    rows = text.split ('\n')

    for idx, row in enumerate (rows):
        thisRow = []

        if len (row) != COLUMNS:
            raise SyntaxError (("Processing file %s\n"+
                                "Incorrect number of columns in row: %d") %
                               (fileName, idx))
        for color in row:
            if color not in colors.keys():
                raise SyntaxError (("Processing file %s\n" + 
                                   "Character is not a color: %s") %
                                   (fileName, color))

            thisColor = colors[color]
            if (thisColor != NONE):
                if idx < level.firstRow:
                    level.firstRow = idx
                if idx > level.lastRow:
                    level.lastRow = idx

            thisRow.append (thisColor)

        level.rows.append (thisRow)

    return level
        

if __name__=='__main__':
    levels = []
    fileNames = [file for file in dircache.listdir('.') if
                 '.lvl' == os.path.splitext (file)[-1]]

    for fileName in fileNames:
        levels.append (Levelify (fileName))

    for level in levels:
        print level


    print """
// This file was dynamically generated. Do not edit it by hand!

//    Copyright 2009 Nathan Michaels
//
//    This file is part of jen-breakout.
//
//    jen-breakout is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 2 of the License, or
//    (at your option) any later version.
//
//    jen-breakout is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with jen-breakout.  If not, see <http://www.gnu.org/licenses/>.

"""
    print
    print 'static level_ptr_t levels[] = {&%s, NULL};' % (', &'.join (
            [level.name for level in levels]),)
